"use strict";

Object.defineProperty(exports, "__esModule", {value: true});
const csharp_1 = require("csharp");
const App = csharp_1.FairyEditor.App;
const FairyGUI = csharp_1.FairyGUI;
const FairyEditor = csharp_1.FairyEditor;
const System = csharp_1.System;

// App.pluginManager.LoadUIPackage(App.pluginManager.basePath + "/" + eval("__dirname") + '/CustomInspector');
App.pluginManager.LoadUIPackage(App.pluginManager.basePath + "/" + eval("__dirname") + '/LoaderImgae');


const CUR_PATH = eval("__dirname");
const Path_Project = CUR_PATH.substr(0, CUR_PATH.indexOf("/"));
const Path_Bin = Path_Project + "/bin/";
const ROOT_PLUGIN = FairyEditor.App.pluginManager.basePath + "/";
// console.log("### CUR_PATH = ", CUR_PATH)
// console.log("### Path_Project = ", Path_Project)
// console.log("### Path_Bin = ", Path_Bin)
// console.log("### ROOT_BIN = ", ROOT_PLUGIN)

let imageCropperWindow;

function createFindPath() {
    let dialog = csharp_1.FairyGUI.UIPackage.CreateObject('LoaderImgae', "FindPath").asCom;
    imageCropperWindow = new csharp_1.FairyGUI.Window();
    imageCropperWindow.contentPane = dialog;
    imageCropperWindow.Center();
    imageCropperWindow.Hide();
    let resourceText = dialog.GetChild("resourceText").asLabel;
    let resourceBtn = dialog.GetChild("resourceBtn").asButton;
    let uiText = dialog.GetChild("uiText").asTextInput;
    let uiBtn = dialog.GetChild("uiBtn").asButton;
    let urlText = dialog.GetChild("urlText").asTextInput;
    let urlBtn = dialog.GetChild("urlBtn").asButton;
    let closeBtn = dialog.GetChild("closeBtn").asButton;
    let tipsText = dialog.GetChild("tipsText").asTextField;

    closeBtn.onClick.Add(() => {
        tipsText.text = "";
        imageCropperWindow.Hide();
    });

    resourceBtn.onClick.Add(() => {
        let url = resourceText.title;
        if (url) {
            let image = App.project.GetItemByURL(url);
            if (image.type == "image") {
                let fpath = unpackeToLoader(image);
                urlText.text = fpath;
                uiText.text = image.GetURL();
            } else {
                tipsText.text = "只可以加载图片资源";
            }
        } else {
            tipsText.text = "请选择需要加载的图片资源！";
        }
    });

    uiBtn.onClick.Add(() => {
        let url = uiText.text;
        let image = App.project.GetItemByURL(url);
        if (image) {
            if (image.type == "image") {
                let fpath = unpackeToLoader(image);
                urlText.text = fpath;
                // uiText.text = image.GetURL();
            } else {
                tipsText.text = "只可以加载图片资源";
            }
        } else {
            tipsText.text = "ui://未查找到资源";
        }
    });

    urlBtn.onClick.Add(() => {
        let url = urlText.text;
        let image = urlToPackageItem(url);
        if (image) {
            if (typeof (image) == 'string') {
                // uiText.text = image.GetURL();
                tipsText.text = image;
            } else {
                // let fpath = unpackeToLoader(image);
                // urlText.text = fpath;
                uiText.text = image.GetURL();
            }
        } else {
            tipsText.text = "未查找到资源";
        }
    });
}


function showAllPackages() {
    // console.log("showAllPackages")
    let document = App.project.allPackages;
    let len = document.Count;
    for (let i = 0; i < len; i++) {
        let ipackage = document.get_Item(i)
        console.log(ipackage.name)
        let items = ipackage.items;
        let itemsLen = items.Count;
        for (let j = 0; j < itemsLen; j++) {
            let item = items.get_Item(j);
            if (item.name == "Shape 1 copy 4") {
                console.log(item.name, item.fileName, item.file, item.path)
            }

            // console.log(item.name,item.fileName,item.file,item.path)
        }
    }
}

function showPackages(pkg) {
    // console.log("showPackages", pkg)
    let ipackage = pkg
    console.log(ipackage.name)
    let items = ipackage.items;
    let itemsLen = items.Count;
    for (let j = 0; j < itemsLen; j++) {
        let item = items.get_Item(j);
        // if (item.name == "Shape 1 copy 4") {
        //     console.log(item.name, item.fileName, item.file, item.path)
        // }

        console.log(item.name, item.fileName, item.file, item.path)
    }
}

function GetPackageItemByUrl(pkg, url) {
    // console.log("GetPackageItemByUrl", url)
    let ipackage = pkg
    let items = ipackage.items;
    let itemsLen = items.Count;
    for (let j = 0; j < itemsLen; j++) {
        let item = items.get_Item(j);
        // if (item.name == "Shape 1 copy 4") {
        //     console.log(item.name, item.fileName, item.file, item.path)
        // }

        if (item.path + item.fileName == url) {
            // console.log(item.name, item.fileName, item.file, item.path)
            return item;
        }
    }
    return null;
}

function settingLoader(url) {
    // console.log("### settingLoader ", url)
    if (url.indexOf("/") == -1) {
        console.log("### remote url error not / ", url)
        return;
    }
    let packageName = url.substr(0, url.indexOf("/"));
    let resUrl = url.substr(url.indexOf("/"), url.length);
    // console.log("### packageName resUrl ", packageName, resUrl)
    // let pkg = App.project.GetPackageByName(packageName)
    // showPackages(pkg)

    // let pkgItem = App.project.GetItemByURL(url);
    // let pkgItem = App.project.GetItemByURL("C:\\wk\\MUD_H5\\tool\\FGUIProject\\assets\\UIBase/img/Shape 1 copy 4.png");
    // console.log(pkgItem.name,pkgItem.fileName,pkgItem.file,pkgItem.path)

    let pkg = App.project.GetPackageByName(packageName)
    let pkgItem = GetPackageItemByUrl(pkg, resUrl);
    if (pkgItem) {
        let obj = App.activeDoc.inspectingTarget;
        if (obj.objectType == "loader") {
            obj.url = pkgItem.GetURL();
            // obj.icon = url;
            obj._url = url;
            obj.clearOnPublish = true;
            // console.log("### ### ", obj.icon, obj.url)
        }
        // console.log(pkgItem.name, pkgItem.fileName, pkgItem.file, pkgItem.path)
    } else {
        console.log("### not find image", url);
    }

}

function urlToPackageItem(url) {
    if (url == "") return;
    if (url.indexOf("ui://") != -1) return "Url地址不正确";
    if (url.indexOf("http://") != -1) return "Url地址不正确";
    if (url.indexOf("https://") != -1) return "Url地址不正确";
    if (url.indexOf("/") == -1) return "Url地址不正确";
    let packageName = url.substr(0, url.indexOf("/"));
    let resUrl = url.substr(url.indexOf("/"), url.length);
    let pkg = App.project.GetPackageByName(packageName)
    let pkgItem = GetPackageItemByUrl(pkg, resUrl);
    if (pkgItem) {
        return pkgItem;
    } else {
        return "未找到地址对应的图片资源";
    }
}

function unpackeToLoader(image) {
    // console.log("### settingLoader ", image)
    if (!image) return;

    let pkgName = image.owner.name;
    let p = image.path
    let f = image.fileName
    let full = pkgName + p + f;
    // console.log("###",pkgName,p,f,full);
    return full;
}


function updateImg(loader, url) {
    // console.log("### not find url", loader, url);
    if (url == "") return;
    if (url.indexOf("ui://") != -1) return;
    if (url.indexOf("http://") != -1) return;
    if (url.indexOf("https://") != -1) return;
    var fullUrl = ROOT_PLUGIN + url;
    // console.log("### fullUrl", fullUrl);
    let img = FairyEditor.VImage.New(fullUrl);
    // let img = FairyEditor.VImage.New( "ui://pz5k4qhbjbta3i" );
    if (img) {
        let texture = new FairyGUI.NTexture(img.ToTexture(true, true));

        //loader.resourceURL = url;
        loader.url = url;
        loader.texture = texture;
    } else {
        console.log("### not find url", loader.name, fullUrl);
    }


}


// 更新激活窗口的 加载器s
function updateLoder() {
    let document = App.activeDoc.content;
    // console.log(document)
    // console.log(document.numChildren)
    for (let i = 0; i < document.numChildren; i++) {
        let item = document.GetChildAt(i);
        // console.log(item.objectType)
        if (item.objectType == "loader") {
            updateImg(item, item.url);
        }
    }
}

function addMenuBtn() {
    let menu = FairyEditor.App.menu.GetSubMenu("tool");
    menu && menu.AddSeperator();//添加分割
    // menu && menu.AddItem("LoaderImgae", "LoaderImgae", (str) => {
    //     updateLoder();
    // });

    // menu && menu.AddItem("App Refresh", "AppRefresh", (str) => {
    //     FairyEditor.App.RefreshProject();
    // });
    menu && menu.AddItem("查找地址", "FindPath", (str) => {
        if (!imageCropperWindow) {
            createFindPath();
        }
        imageCropperWindow.Show();
    });

}


App.add_onProjectOpened(() => {
    // console.log("### open project = ")
    // createFindPath();
    addMenuBtn();
});


class LoaderAppendInspector extends csharp_1.FairyEditor.View.PluginInspector {
    constructor() {
        super();
        // this.panel = csharp_1.FairyGUI.UIPackage.CreateObject("CustomInspector", "Component1").asCom;
        this.panel = csharp_1.FairyGUI.UIPackage.CreateObject("LoaderImgae", "LoaderImgae").asCom;
        this.inputText = this.panel.GetChild("inputText").asTextInput;
        this.inputLoader = this.panel.GetChild("inputLoader").asLoader;
        this.inputResource = this.panel.GetChild("inputResource").asLabel;
        this.btnResource = this.panel.GetChild("btnResource").asButton;

        // let sels = App.activeDoc.inspectingTargets;
        // let obj = sels.get_Item(0);
        let obj = App.activeDoc.inspectingTarget;
        console.log("select target ", obj.objectType, obj.id, obj.customData);
        if (obj.objectType == "loader") {
            // console.log("select target ", obj.id,obj.customData);
            if (obj.customData) {
                this.inputText.text = obj.customData;
            }
        }


        this.inputText.onFocusOut.Add(() => {
            // let url = FairyGUI.UIPackage.GetItemURL("UIBase", "VIP_png");
            // console.log("onFocusOut");
            // showAllPackages();

            let obj = App.activeDoc.inspectingTarget;
            if (obj.objectType == "loader") {
                obj.docElement.SetProperty("customData", this.inputText.text);
            }
            settingLoader(this.inputText.text);
        })
        // this.inputText.onChanged.Add(() => {
        //     // console.log("onChanged");
        // })
        // this.inputText.onSubmit.Add(() => {
        //     console.log("onSubmit");
        // })
        this.updateAction = () => {
            return this.updateUI();
        };
        // this.disposeAction = () => {
        //     console.log("disposeAction");
        // };
        // console.log("###",this.inputResource);
        this.btnResource.onClick.Add(() => {
            let url = this.inputResource.title;
            if (url) {
                let image = App.project.GetItemByURL(url);
                if (image.type == "image") {
                    let fpath = unpackeToLoader(image);
                    this.inputText.text = fpath;
                    let obj = App.activeDoc.inspectingTarget;
                    if (obj.objectType == "loader") {
                        obj.docElement.SetProperty("customData", this.inputText.text);
                    }
                    settingLoader(this.inputText.text);
                } else {
                    console.log("###只可以加载图片资源！");
                }
            } else {
                console.log("###请选择需要加载的图片资源！");
            }
        })
    }

    updateUI() {
        // console.log("updateAction");
        let obj = App.activeDoc.inspectingTarget;
        // console.log("select target ", obj.objectType, obj.id, obj.customData);
        if (obj.objectType == "loader") {
            // console.log("select target ", obj.id,obj.customData);
            if (obj.customData) {
                this.inputText.text = obj.customData;
            } else {
                this.inputText.text = "";
            }
            // this.inputResource.title = "";
            // this.inputResource.icon = "";
            this.inputResource.text = "";
        }
        // let sels = App.activeDoc.inspectingTargets;
        // let obj = sels.get_Item(0);
        // this.combo.value = obj.customData;

        // let count = App.inspectorView.visibleInspectors.Count;
        // console.log("select visibleInspectors ", count);
        // for (let i = 0; i < count; i++) {
        //     let item = App.inspectorView.visibleInspectors.get_Item(i);
        //     console.log("select target ", obj.objectType, item);
        // }
        return true; //if everything is ok, return false to hide the inspector
    }

    UpdateUI() {
        console.log("UpdateUI");
    }

    Dispose() {
        console.log("Dispose");
    }
}

//Register a inspector
// App.inspectorView.AddInspector(() => new LoaderAppendInspector(), "LoaderImgae", "设置Res资源连接");
//Condition to show it
// App.docFactory.ConnectInspector("LoaderImgae", "loader", false, false);

// App.docFactory.ConnectInspector("LoaderImgae", "mixed", false, false);


exports.onDestroy = exports.onPublish = void 0;
//function onPublish(handler) {
//    console.log("### onPublish ",handler.fileName);
//    let pkg = handler.GetItemDesc(null);
//    let id = pkg.GetAttribute("id");
//    let match = id.match(/\$\w+/g); // 根据标识符$进行窜改
//    console.log("### onPublish2 ",pkg);
//    console.log("### onPublish3 ",id);
//    if (match) {
//        let tag = match[0];
//        id = id.replace(tag, "");
//        pkg.SetAttribute("id", id);
//        handler.ExportBinaryDesc(pkg.ToString());
//    }
//}

function findUIPath(url) {
    let image = App.project.GetItemByURL(url);
    if (image) {
        // console.log(image.name, image.fileName, image.file, image.path,image.owner.name)
        if (image.type == "image" && image.owner.name == "res") {
            let fpath = unpackeToLoader(image);
            return fpath
            // uiText.text = image.GetURL();
        } else {
            // tipsText.text = "只可以加载图片资源";
            return "";
        }
    } else {
        // tipsText.text = "ui://未查找到资源";
        return "";
    }
}


function paresXml(xml) {
	if(!xml)return;
    // console.log("### xml ", xml.name, xml.text);
    let xmlAttributeCount = xml.attributes.Count;
    // console.log("### xmlAttributeCount ", xmlAttributeCount);
    if (xmlAttributeCount > 0) {
        let myEnumerator = xml.attributes.GetEnumerator();
        let modifyList = [];
        // console.log("###", myEnumerator.Current, myEnumerator.Current.Key, myEnumerator.Current.Value);

        while (myEnumerator.MoveNext()) {
            // console.log("###", myEnumerator.Current, myEnumerator.Current.Key, myEnumerator.Current.Value);
            let itemKey = myEnumerator.Current.Key;
            let itemValue = myEnumerator.Current.Value;
            if (itemValue && itemValue.indexOf("ui://") != -1) {

                let fpath = findUIPath(itemValue);
                if (fpath && fpath != "") {
                    modifyList.push([itemKey, fpath])
                    // xml.SetAttribute(itemKey, fpath);
                    // xml.attributes.set_Item(itemKey,fpath);
                    // console.log("### replace URL ", itemKey, fpath);
                }
            }
        }

        for (let j = 0; j < modifyList.length; j++) {
            xml.SetAttribute(modifyList[j][0], modifyList[j][1]);
        }
    }

    let count = xml.elements.Count;
    for (let i = 0; i < count; i++) {
        let elementsXml = xml.elements.get_Item(i);
        // console.log("### elementsXml " + i, elementsXml.name, elementsXml.text);
        paresXml(elementsXml);
    }
}

function onPublish(handler) {
    // console.log("### onPublish ", handler, handler.fileName);
    let pkg = handler.pkg;
    // console.log("### pkg ", pkg);
    let count = pkg.items.Count;
    // console.log("pkg.items ", count);
    for (let i = 0; i < count; i++) {
        let item = pkg.items.get_Item(i);
        if (item.type == "component") {

            // console.log("pkg.items ", item.objectType, item.type, item);
            let pkg = handler.GetItemDesc(item);
            paresXml(pkg);

        }
    }
    // let settings = handler.project.GetSettings("Publish").codeGeneration;
}

exports.onPublish = onPublish;

function onDestroy() {
// do cleanup here
}

exports.onDestroy = onDestroy;
